<template>
  <div>
    <p>{{ vTitle }}</p>

    <div class="my-3 text-primary">
      <p>{{ append }}</p>
    </div>

    <div class="flex-center">
      <el-input v-model="todo" type="text" class="form-control" />
      <el-button type="primary" class="btn btn-primary" @click="add">Add</el-button>
    </div>
    <p>[TodoLength: {{ todoLength }}, 数量: {{ itemsQuantity }}]</p>

    <div class="list-group">
      <div
        class="flex-center"
        v-for="(item,index) in items"
        :key="index"
      >
        <span class="card-style">{{ item }}</span>
        <button class="close" @click="remove(index)">
          <span>&times;</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch, onBeforeMount, onMounted } from 'vue'

export default {
  props: {
    title: {
      type: String,
      default: ''
    },
    initInput: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    const vTitle = computed(() => '-' + props.title + '-')

    const todo = ref(props.initInput)
    const todoLength = ref(0)

    const items = ref(['A', 'B'])
    const itemsQuantity = computed(() => items.value.length)
    const append = ref('')

    watch(
      // 一个想要侦听的响应式引用
      todo,
      // 一个回调
      (todo) => {
        console.log('todo', todo)
        todoLength.value = todo.length
      },
      // 可选的配置选项
      {
        immediate: true
      }
    )

    watch(
      // getter
      () => items.value,
      // callback
      (items) => {
        append.value = ''
        items.forEach(item => {
          append.value += item + ' '
        })
      },
      // watch Options
      {
        immediate: true,
        deep: true
      }
    )

    const add = () => {
      if (todo.value) {
        items.value.push(todo.value)
        todo.value = ''
      }
    }

    const remove = index => {
      items.value.splice(index, 1)
    }

    onBeforeMount(() => {
      console.log('V3 beforeMount!')
    })

    onMounted(() => {
      console.log('V3 mounted!')
    })

    return {
      vTitle,
      todo,
      todoLength,
      items,
      itemsQuantity,
      append,
      add,
      remove
    }
  }
}
</script>

<style lang="less">
@import '~@/common/less/normal.less';
</style>
